<template>
    <el-form ref="formRef" :model="form" label-suffix="：" labelWidth="120px">
        <el-steps :active="active">
            <template v-for="(step, index) in steps" :key="index">
                <el-step>
                    <template #title>
                        <span class="step-title" @click="active = step.value">{{ step.title }}</span>
                    </template>
                </el-step>
            </template>
        </el-steps>
        <div v-show="active === 1" class="step1">
            <el-form-item label="节点名称">
                <el-input v-model="form.nodeName"></el-input>
            </el-form-item>
            <el-form-item label="节点ID">
                <el-input v-model="form.typeConcatName" disabled></el-input>
            </el-form-item>
            <el-form-item :label="nodeLabel === '字段名映射'?'源节点':'数据所在节点'">
                <el-select v-model="form.sourceNode" @change="fNodeChange">
                    <el-option
v-for="item in fNodeList"
                               :key="item.name"
                               :label="`${item.nodeName} (${item.name})`"
                               :value="item.name"/>
                </el-select>
            </el-form-item>
            <el-form-item label="目的节点" v-if="nodeLabel === '字段名映射'">
                <el-select v-model="form.targetNode" @change="tNodeChange">
                    <el-option
v-for="item in tNodeList"
                               :key="item.name"
                               :label="`${item.nodeName} (${item.name})`"
                               :value="item.name"/>
                </el-select>
            </el-form-item>
            <el-form-item label="备注">
                <el-input v-model="form.remark" placeholder="请输入内容" type="textarea"/>
            </el-form-item>
            <dialog-footer ok-text="保存" @cancel="cancel" @ok="submitForm">
                <el-button type="success" @click="active = 2">下一步</el-button>
            </dialog-footer>
        </div>
        <div v-show="active === 2" class="step2">
            <div v-if="nodeLabel === '字段名映射'">
                <div class="flex-center">
                    <el-button size="small" type="primary" @click="handleSort('sameName')">同名映射</el-button>
                    <el-button size="small" type="primary" @click="handleSort('sameRow')">同行映射</el-button>
                    <el-button size="small" type="primary" @click="handleSort('reset')">重置</el-button>
                </div>
                <el-row style="height: 550px; margin: 10px 0">
                    <el-col :offset="4" :span="8">
                        <div class="flex items-center">
                            <span>源端表字段</span>
                            <el-checkbox v-model="form.fCheckAll" class="ml-10px" @change="fHandleCheckAllChange">全选</el-checkbox>
                        </div>
                        <el-scrollbar class="mt-5px" height="500px">
                            <draggable
                                :group="{ name: 'drag', pull: false, put: false }"
                                :list="form.fColumnList || []"
                                :scroll-speed="200"
                                chosen-class="chosenClass"
                                class="draggable-main"
                                ghost-class="ghost"
                                item-key="left"
                            >
                                <template #item="{ element, index }">
                                    <div>
                                        <el-row>
                                              <el-col :span="2">
                                                  <div class="no">
                                                      <span>{{ index + 1 }}</span>
                                                  </div>
                                              </el-col>
                                              <el-col :span="22">
                                                  <div class="item">
                                                      <el-checkbox v-model="element.isChecked">
                                                          {{ element.name }}
                                                      </el-checkbox>
                                                  </div>
                                              </el-col>
                                          </el-row>
                                    </div>
                                </template>
                            </draggable>
                        </el-scrollbar>
                    </el-col>
                    <el-col :offset="4" :span="8">
                        <div class="flex items-center">
                            <span>目的端表字段</span>
                            <el-checkbox v-model="form.tCheckAll" class="ml-10px" @change="tHandleCheckAllChange">全选</el-checkbox>
                        </div>
                        <el-scrollbar class="mt-5px" height="500px">
                            <draggable
                                :group="{ name: 'drag', pull: false,put: false }"
                                :list="form.tColumnList || []"
                                :scroll-speed="200"
                                chosen-class="chosenClass"
                                class="draggable-main"
                                ghost-class="ghost"
                                item-key="left"
                            >
                                <template #item="{ element, index }">
                                    <div>
                                        <el-row>
                                            <el-col :span="2">
                                                <div class="no">
                                                    <span>{{ index + 1 }}</span>
                                                </div>
                                            </el-col>
                                            <el-col :span="22">
                                                <div class="item">
                                                    <el-col :span="22">
                                                        <el-checkbox v-model="element.isChecked">
                                                            {{ element.name }}
                                                        </el-checkbox>
                                                    </el-col>
                                                </div>
                                            </el-col>
                                        </el-row>
                                    </div>
                                </template>
                            </draggable>
                        </el-scrollbar>
                    </el-col>
                </el-row>
                <dialog-footer ok-text="保存" @cancel="cancel" @ok="submitForm">
                    <el-button type="success" @click="active = 1">上一步</el-button>
                </dialog-footer>
            </div>

            <div v-if="nodeLabel === '字段值格式化'">
                <el-form-item>
                    <div style="margin-bottom: 10px;">
                        <el-button
                            size="small"
                            type="primary"
                            @click="addField"
                        >新增字段</el-button>
                        <el-button
                            :disabled="selectedRows.length === 0"
                            size="small"
                            type="danger"
                            @click="batchDelete"
                        >删除选中</el-button>
                    </div>
                    <el-table :data="form.fields.meta" style="width: 100%" @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="30"/>
                        <el-table-column align="center" header-align="center" label="序号" width="50">
                            <template #default="scope">
                                {{ scope.$index + 1 }}
                            </template>
                        </el-table-column>
                        <el-table-column label="字段名" prop="name" width="150">
                            <template #default="scope">
                                <el-select v-model="scope.row.name">
                                    <el-option
                                        v-for="item in form.fColumnList"
                                        :key="item.name"
                                        :label="item.name"
                                        :value="item.name"
                                    />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="字段类型" prop="type" width="150">
                            <template #default="scope">
                                <el-select v-model="scope.row.type">
                                    <el-option
                                        v-for="item in typeList"
                                        :key="item.dictLabel"
                                        :label="item.dictLabel"
                                        :value="item.dictLabel"
                                    />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="字段格式" prop="conversion_mask" width="150">
                            <template #default="scope">
                                <el-select v-model="scope.row.conversion_mask">
                                    <el-option
                                        v-for="item in formatList"
                                        :key="item.dictValue"
                                        :label="item.dictLabel"
                                        :value="item.dictValue"
                                    />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="120">
                            <template #default="scope">
                                <el-button
                                    size="small"
                                    type="danger"
                                    @click="deleteField(scope.$index)"
                                >删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <dialog-footer ok-text="保存" @cancel="cancel" @ok="submitForm">
                    <el-button type="success" @click="active = 1">上一步</el-button>
                </dialog-footer>
            </div>
        </div>
    </el-form>

</template>

<script setup>
import {computed, defineComponent, onMounted, onUnmounted, reactive, ref, watch} from 'vue';
import {flowServiceStore} from '@data/store/flow';
import {storeToRefs} from 'pinia';
import {selectTables, selectSchema, selectColumns, selectTableInfo} from '@data/api/data/datacollection'
import {search as datasourceList} from '@data/api/data/datasource'
import {getCommonStepInputFields} from '@data/api/data/dataDevelopment'
import { getDicts } from '@base/api/base/dict/data'
import {ElMessage} from "element-plus";
import {cloneDeep} from "lodash-es";
import Draggable from "vuedraggable";



const flowCount = flowServiceStore();

const {graph, flowData} = storeToRefs(flowCount);

defineComponent({
    name: 'SelectValues',
});

const props = defineProps({
    detailObject: {
        type: Object,
        default: () => {
        },
    },
})
const nodeLabel = props.detailObject.data.label

const steps = ref([
    {value: 1, title: '基础属性'},
    {value: 2, title: `${nodeLabel === '字段名映射' ? '字段映射' : '字段格式'}`}
]);
const active = ref(1);

const loading = ref(false);

const fNodeList = computed(() => {
    return Object.entries(flowData.value)
        .filter(([nodeId, node]) => nodeId !== props.detailObject.id && node.type !== 'edge' && node.type !== 'Edge')
        .map(([name, node]) => ({
          name,
          ...node
        }))
})
const tNodeList = computed(() => {
    return Object.entries(flowData.value)
        .filter(([nodeId, node]) => nodeId !== props.detailObject.id && node.type !== 'edge' && node.type !== 'Edge')
        .map(([name, node]) => ({
          name,
          ...node
        }))
})
// 在SelectValues组件中获取下游节点
// const getDownstreamNodes = (currentNodeId) => {
//   if (!graph.value) return []
//   return graph.value.getOutgoingEdges(currentNodeId)
//       ?.map(edge => {
//         const node = graph.value.getCellById(edge.target.cell)
//         return {
//           ...flowData.value[node.name] // 获取存储在flowData中的节点数据
//         }
//       })
//       ?.filter(node => node?.type === 'TableOutput') || []
// }

const form = reactive({
    nodeName: '',
    name: '',
    type: 'SelectValues',
    copies: 1,
    distribute: 'Y',
    sourceNode: '',
    targetList: '',
    targetTable: '',
    remark: '',
    fields: {
        field: [
            {
                name: '',
                rename: '',
                length: '',
                precision: '',
            }
        ],
        meta: [
            {
                name: '',
                type: '',
                format: '',
            }
        ]
    },

    GUI: {
        xloc: 1,
        yloc: 1,
        draw: 'Y'
    }

});

const emit = defineEmits(['cancel']);

onMounted(async () => {
    getTypeList();
    getFormatList();
    form.nodeName = flowData.value[props.detailObject.id]?.nodeName || props.detailObject.data.label;
    form.name = props.detailObject.id;
    form.typeConcatName = `${props.detailObject.id}(${form.type}-${props.detailObject.id})`;
    form.sourceNode = flowData.value[props.detailObject.id]?.sourceNode || '';
    form.targetNode = flowData.value[props.detailObject.id]?.targetNode || '';
    form.remark = flowData.value[props.detailObject.id]?.remark || '';

    const fields = flowData.value[props.detailObject.id]?.fields || {};
    form.fields = {
        field: cloneDeep(fields.field) || [],
        meta: cloneDeep(fields.meta) || []
    };
    form.fColumnList = cloneDeep(flowData.value[props.detailObject.id]?.fColumnList) || [];
    form.fColumnListRaw = cloneDeep(flowData.value[props.detailObject.id]?.fColumnListRaw) || [];
    // if(form.fColumnList?.length === 0){
    //   const params = {
    //     ktrJsonContent: JSON.stringify(setData()),
    //     stepName: "字段名映射"
    //   }
    //   await getCommonStepInputFields(params).then(res => {
    //     console.log(res)
    //     if (res.data?.length) {
    //       form.fColumnList = res.data;
    //       form.fColumnListRaw = cloneDeep(form.fColumnList);
    //       form.fields.field = res.data.map((item, index) => ({
    //         ...(form.fields.field[index] || {}), // 保留原有字段的其他属性
    //         name: item.name || '' // 使用接口返回的 name 覆盖
    //       }))
    //     } else {
    //       form.fields.field = [{
    //         name: '',
    //         rename: '',
    //         length: '',
    //         precision: '',
    //       }]
    //     }
    //   })
    // }
    // if(form.sourceNode){
    //   // 获取源节点名称
    //   const sourceNodeName = fNodeList.value.find(node => node.id === form.sourceNode)?.name || '';
    //
    //   const params = {
    //     ktrJsonContent: JSON.stringify(setData()),
    //     stepName: sourceNodeName
    //   }
    //   console.log(params)
    //   await getCommonStepInputFields(params).then(res => {
    //     console.log(res)
    //     if (res.data?.length) {
    //       const newColumns = res.data;
    //       const oldColumns = flowData.value[props.detailObject.id]?.fColumnList || [];
    //
    //       // 创建旧字段顺序映射表
    //       const orderMap = new Map();
    //       oldColumns.forEach((item, index) => {
    //         orderMap.set(item.name, index);
    //       });
    //
    //       // 分离选中和未选中字段
    //       const [matchedColumns, newUnmatchedColumns] = newColumns.reduce(([matched, unmatched], item) => {
    //         if (orderMap.has(item.name)) {
    //           matched.push(item);
    //         } else {
    //           unmatched.push(item);
    //         }
    //         return [matched, unmatched];
    //       }, [[], []]);
    //
    //       // 按照旧字段顺序排序
    //       matchedColumns.sort((a, b) => orderMap.get(a.name) - orderMap.get(b.name));
    //
    //       // 合并字段并保留选中状态
    //       form.fColumnList = [
    //         ...matchedColumns.map(item => ({
    //           ...item,
    //           isChecked: oldColumns.find(c => c.name === item.name)?.isChecked || false
    //         })),
    //         ...newUnmatchedColumns.map(item => ({
    //           ...item,
    //           isChecked: false
    //         }))
    //       ];
    //
    //       // 保留原始数据
    //       form.fColumnListRaw = cloneDeep(form.fColumnList);
    //
    //       // 同步到字段配置
    //       form.fields.field = form.fColumnList.map((item, index) => ({
    //         ...(form.fields.field[index] || {}),
    //         name: item.name || ''
    //       }));
    //     }   else {
    //       form.fields.field = [{
    //         name: '',
    //         rename: '',
    //         length: '',
    //         precision: '',
    //       }]
    //
    //         console.log('form.fColumnList',flowData.value[form.sourceNode]?.fields)
    //         console.log(flowData.value[form.targetNode]?.fields)
    //
    //         form.fColumnList = cloneDeep(flowData.value[form.sourceNode]?.fields?.field) || [];
    //         form.tColumnList = cloneDeep(flowData.value[form.targetNode]?.fields?.field) || [];
    //
    //     }
    //   })
    // }
    // console.log(props.detailObject.id)

    form.tColumnList = cloneDeep(flowData.value[props.detailObject.id]?.tColumnList) || [];
    form.tColumnListRaw = cloneDeep(flowData.value[props.detailObject.id]?.tColumnList) || [];
    if(form.sourceNode)fNodeChange(form.sourceNode);
    if(form.targetNode)tNodeChange(form.targetNode);
    form.tColumnList = cloneDeep(flowData.value[props.detailObject.id]?.tColumnList) || [];
    form.tColumnListRaw = cloneDeep(flowData.value[props.detailObject.id]?.tColumnList) || [];
    form.fCheckAll = allFColumnChecked.value;
    form.tCheckAll = allTColumnChecked.value;

    form.distribute = flowData.value[props.detailObject.id]?.distribute || 'Y';

})

// 全选逻辑处理
const fHandleCheckAllChange = (val) => {
    form.fColumnList.forEach(item => {
        item.isChecked = val;
    })
}
const tHandleCheckAllChange = (val) => {
    form.tColumnList.forEach(item => {
        item.isChecked = val;
    })
}
const allFColumnChecked = computed(() => {
    return form.fColumnList?.length > 0 && form.fColumnList.every(item => item.isChecked);
});
const allTColumnChecked = computed(() => {
    return form.tColumnList?.length > 0 && form.tColumnList.every(item => item.isChecked);
});
// watch(() => flowData.value, () => {
//   const outputNodes = getDownstreamNodes(props.detailObject.id)
//   if(outputNodes.length > 0){
//     const firstOutput = flowData.value[outputNodes[0]]
//     // 更新目标数据源和表
//     form.targetList = firstOutput.datasourceId
//     form.targetTable = firstOutput.table
//     form.datasourceType = firstOutput.datasourceType
//     // 触发字段加载
//     getTableColumns()
//   }
// }, { deep: true })
watch(() => form.fColumnList, (newList) => {
    form.fCheckAll = allFColumnChecked.value;
}, {deep: true});
watch(() => form.tColumnList, (newList) => {
    form.tCheckAll = allTColumnChecked.value;
}, {deep: true});


// watch(() => form.sourceNode, (key) => {
//
//     if(!key){
//       form.fColumnList = [];
//       form.fColumnListRaw = [];
//       return
//     }
//     const rawColumns = cloneDeep(flowData.value[key]?.fields?.field) || [];
//     form.fColumnList = rawColumns.map(item => ({
//         name: item.column_name
//     }));
//     form.fColumnListRaw = cloneDeep(form.fColumnList);
// }, { deep: true });

// watch(() => form.targetNode, (key) => {
//
//     if(!key){
//       form.tColumnList = [];
//       form.tColumnListRaw = [];
//       return
//     }
//     flowData.value[key]?.fields.field.map(item => {
//       item.name = item.column_name;
//     })
//     const rawColumns = cloneDeep(flowData.value[key]?.fields.field) || [];
//     form.tColumnList = rawColumns.map(item => ({
//         name: item.column_name
//     }));
//     form.tColumnListRaw = cloneDeep(form.tColumnList);
// }, { deep: true });


// 监听源节点字段变化
watch(
    () => flowData.value[form.sourceNode]?.fields?.field,
    (newVal, oldVal) => {
        if (form.sourceNode && newVal && JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
            // 创建旧字段的映射表用于保留选中状态
            const oldFieldsMap = new Map();
            (form.fColumnList || []).forEach(item => {
                oldFieldsMap.set(item.name, item.isChecked);
            });
            console.log('oldFieldsMap', oldFieldsMap)
            // 合并新旧字段的选中状态
            form.fColumnList = cloneDeep(newVal.map(item => ({
                // ...item,
                name: item.name,
                isChecked: oldFieldsMap.has(item.name) ? oldFieldsMap.get(item.name) : false
            })));
            console.log('form.fColumnList', form.fColumnList)
        }
    },
    {deep: true}
);

// 监听目标节点字段变化
watch(
    () => flowData.value[form.targetNode]?.fields?.field,
    (newVal, oldVal) => {
        if (form.targetNode && newVal && JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
            // 创建旧字段的映射表用于保留选中状态
            const oldFieldsMap = new Map();
            console.log('tColumnList1', form.tColumnList);
            (form.tColumnList || []).forEach(item => {
                oldFieldsMap.set(item.name, item.isChecked);
            });

            // 合并新旧字段的选中状态
            form.tColumnList = cloneDeep(newVal.map(item => ({
                // ...item,
                name: item.name,
                isChecked: oldFieldsMap.has(item.name) ? oldFieldsMap.get(item.name) : false
            })));
        }
    },
    {deep: true}
);

// 中间步骤获取字段方法的请求Json
const setData = () => {

    let arr = graph.value.toJSON().cells.filter(item => item.shape !== "edge" && item.shape !== 'start-node' && item.shape !== 'end-node');

    arr = arr.map(element => {
        return {
            // ...element,
            name: element.data.label,
            type: element.data.component,
            id: element.id,
            ...flowData.value[element.id]
        }
    })

    let lineArr = graph.value.toJSON().cells.filter(item =>
        item.shape === "edge" &&
        graph.value.toJSON().cells.find(e => e.id === item.source.cell).shape !== "start-node" &&
        graph.value.toJSON().cells.find(e => e.id === item.target.cell).shape !== 'end-node'
    );


    let hop = [];
    lineArr.map(item => {
        hop.push({
            from: flowData.value[item.source.cell]?.name,
            to: flowData.value[item.target.cell]?.name,
            enabled: 'Y'
        })
    })


    let connection = arr.map(item => {
        return {
            name: item.connection,
        }
    }).filter(item => item.name) // 过滤掉name为undefined/null/空的情况

    let uniqueArray = Object.values(connection.reduce((acc, cur) => {
        if (cur.name) { // 增加有效性判断
            acc[cur.name] = cur; // 如果存在相同的name，则后一个会覆盖前一个，保证了唯一性
        }
        return acc;
    }, {}));
    console.log("uniqueArray", uniqueArray)

    return {
        transformation: {
            ...(uniqueArray.length > 0 && {connection: uniqueArray.length === 1 ? uniqueArray[0] : uniqueArray}),
            // connection: uniqueArray.length == 1 ? uniqueArray[0] : uniqueArray,
            order: {
                hop: arr.length === 1 ?
                    {
                        "from": arr[0].name,
                        "to": arr[1].name,
                        "enabled": "Y"
                    } : hop//transformData(arr),
            },
            step: arr
        }
    };
}

const fNodeChange = async (e) => {
    // fNodeList.value.find(item => {
    //   if (item.id === e) {
    //     form.fColumnList = item.fields?.field
    //   }
    // })
    // const sourceNodeName = fNodeList.value.find(node => node.name === form.sourceNode)?.name || '';
    //
    // const params = {
    //   ktrJsonContent: JSON.stringify(setData()),
    //   stepName: sourceNodeName
    // }
    // await getCommonStepInputFields(params).then(res => {
    //   console.log(res)
    //   if (res.data?.length) {
    //     form.fColumnList = res.data;
    //     form.fColumnListRaw = cloneDeep(form.fColumnList);
    //     form.fields.field = res.data.map((item, index) => ({
    //       ...(form.fields.field[index] || {}), // 保留原有字段的其他属性
    //       name: item.name || '' // 使用接口返回的 name 覆盖
    //     }))
    //     console.log(form.fColumnList)
    //   } else {
    //     form.fields.field = [{
    //       name: '',
    //       rename: '',
    //       length: '',
    //       precision: '',
    //     }]
    //   }
    // })
    // 获取新的源节点字段列表
    const currentSourceNode = fNodeList.value.find(item => item.name === e);
    const newColumns = cloneDeep(currentSourceNode.fieldList || []);
    // 创建旧字段的选中状态映射表
    const checkedMap = new Map();
    (form.fColumnList || []).forEach(item => {
        checkedMap.set(item.name, item.isChecked);
    });
    // 合并新旧字段，保留选中状态
    form.fColumnList = newColumns.map(item => ({
        ...item,
        isChecked: checkedMap.has(item.name) ? checkedMap.get(item.name) : false
    }));
}
const tNodeChange = (e) => {
    const currentSourceNode = tNodeList.value.find(item => item.name === e);
    const newColumns = cloneDeep(currentSourceNode?.fields?.field || []);
    // 创建旧字段的选中状态映射表
    const checkedMap = new Map();
    (form.tColumnList || []).forEach(item => {
        checkedMap.set(item.name, item.isChecked);
    });
    // 合并新旧字段，保留选中状态
    form.tColumnList = newColumns.map(item => ({
        ...item,
        isChecked: checkedMap.has(item.name) ? checkedMap.get(item.name) : false
    }));
}

// 映射方式按钮处理
const handleSort = (type) => {
    if (type === 'sameName') {
        form.fColumnList.forEach(item => item.isChecked = false);
        form.tColumnList.forEach(item => item.isChecked = false);
        const fColumnList = form.fColumnList || [];
        const tColumnList = form.tColumnList || [];
        const nameIndexMap = new Map();
        fColumnList.forEach((item, index) => {
            nameIndexMap.set(item.name, index);
        });

        const sortedFColumnList = fColumnList.filter(item => tColumnList.some(tItem => tItem.name === item.name))
            .concat(fColumnList.filter(item => !tColumnList.some(tItem => tItem.name === item.name)));

        form.fColumnList = sortedFColumnList;

        setTimeout(() => {
            const sortedTColumnList = new Array(fColumnList.length).fill(null);
            tColumnList.forEach(item => {
                const index = nameIndexMap.get(item.name);
                if (index !== undefined) {
                    sortedTColumnList[index] = item;
                }
            });
            const remainingItems = tColumnList.filter(item => !sortedTColumnList.includes(item));
            sortedTColumnList.push(...remainingItems);
            form.tColumnList = sortedTColumnList.filter(item => item !== null);

            let num = 0;
            form.fColumnList.map((item, index) => {
                if (form.tColumnList[index] && form.tColumnList[index].name === item.name) {
                    num++;
                }
            })
            for (let i = 0; i < num; i++) {
                form.fColumnList[i].isChecked = true;
                form.tColumnList[i].isChecked = true;
            }
        }, 50);
    } else if (type === 'sameRow') {
        const length = Math.min(form.fColumnList?.length || 0, form.tColumnList?.length || 0);
        form.fColumnList.forEach(item => item.isChecked = false);
        form.tColumnList.forEach(item => item.isChecked = false);
        for (let i = 0; i < length; i++) {
            form.fColumnList[i].isChecked = true;
            form.tColumnList[i].isChecked = true;
        }
    } else if (type === 'reset') {
        fHandleCheckAllChange(false)
        tHandleCheckAllChange(false)
    }
};

const submitForm = () => {
    // 新增校验逻辑
    const selectedFCount = form.fColumnList?.filter(item => item.isChecked) || [];
    const selectedTCount = form.tColumnList?.filter(item => item.isChecked) || [];

    if (selectedFCount.length !== selectedTCount.length) {
        ElMessage.error('源端和目的端字段选择数量不一致，请检查映射关系');
        return; // 阻止提交
    }
    if (nodeLabel === '字段名映射'){
        form.fields.field = [];
        selectedFCount.forEach((fItem, index) => {
            const tItem = selectedTCount[index];
            form.fields.field.push({
                name: fItem.name,
                rename: tItem.name,
                length: '',
                precision: ''
            });
        });
    }
    flowCount.setFlowData({
        ...flowData.value,
        [props.detailObject.id]: {
            ...form,
            name: `${form.type}-${form.name}`,
        }
    })
    console.log(flowData.value);
    emit('cancel');

}
const cancel = () => {
    emit('cancel');
}

const toReader = () => {

}

const parseSql = () => {
}

// 字段值格式化部分逻辑
const typeList = ref([]);
const getTypeList= () => {
    getDicts('ktr_field_type').then((response) => {
        typeList.value = response.data
    })
};
const formatList = ref([]);
const getFormatList= () => {
    getDicts('date_format').then((response) => {
        formatList.value = response.data
    })
};

const selectedRows = ref([])
const handleSelectionChange = (val) => {
    selectedRows.value = val
}
const batchDelete = () => {
    if (selectedRows.value.length === 0) return
    const indexes = selectedRows.value.map(row =>
        form.fields.meta.indexOf(row)
    ).sort((a, b) => b - a)
    indexes.forEach(index => {
        form.fields.meta.splice(index, 1)
    })
    selectedRows.value = []
}
const addField = () => {
    form.fields.meta.push({
        name: '',
        type: 'String',
        format: '',
    });
}
const deleteField = (index) => {
    form.fields.meta.splice(index, 1);
}

</script>

<style scoped lang="scss">
.draggable-main {
    min-height: 28px;

    .item {
        border-radius: 2px;
        user-select: none;
        padding: 2px 10px;
        margin-bottom: 4px;
        box-sizing: border-box;
        background-color: #f0f2f5;

        &:hover {
            background-color: #dcdfe6;
            cursor: move;
        }
    }

    .no {
        margin-top: 6px;
        width: 20px;
        text-align: center;
    }
}

.ghost {
    background-color: #409eff !important;
    color: #fff;
}

.flex-center {
    display: flex;
    align-items: center;
    justify-content: center;
}

.selector-container {
    width: 100%;
    display: flex;
    align-items: center;
}

.step-title {
    cursor: pointer;
    transition: color 0.3s;
}

.step-title:hover {
    color: #409eff;
}
</style>